#include <stdio.h>
#include <time.h>
#include <unistd.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <signal.h>
#include <stdlib.h>

#include <string.h>

void sighandler(int signum){
    printf("--接收信号(%s)--\n", strsignal(signum));
    printf("\033[?25h");
    kill(0, SIGKILL);
}

int main(int argc, char const *argv[])
{

    int fds[2];
    if(pipe(fds) != 0) return -1;

    char buf[64] = "";
    if(fork() == 0){
        close(fds[0]); // 关闭读
        // dup2(fds[1], 1);  // 重定向1到 fds[1]
        while(1){
            time_t t1= time(NULL);
            struct tm *t2 = localtime(&t1);
            bzero(buf, 64);
            // 向管道中写入数据
            sprintf(buf,"%04d-%02d-%02d %02d:%02d:%02d\n",
                t2->tm_year+1900,
                t2->tm_mon+1,
                t2->tm_mday, t2->tm_hour, t2->tm_min, t2->tm_sec);
            write(fds[1], buf, strlen(buf));
            sleep(1);
        }
        _exit(0);
    }
    struct sigaction sa; 
    memset(&sa, 0, sizeof(sa));
    sa.sa_handler = sighandler;
    
    sigemptyset(&sa.sa_mask); // 清空信号集
    sigaddset(&sa.sa_mask, SIGINT); // 添加CTRL+C的信号处理
    
    if(sigaction(SIGINT, &sa, NULL) == -1) return -1;
 
    while(1){
        close(fds[1]);
        bzero(buf, 64);
        if(read(fds[0], buf, 64) != 0 ){
            printf("\033[2J\033[1;1H\033[?25l");
            printf("----显示当前时间（按Ctrl+C退出）---\n");
            printf("%s",  buf);
        }
    }
    wait(NULL);
    return 0;
}
